package com.accp.dao.impl;

import com.accp.dao.ComputerDao;
import com.accp.pojo.Computer;
import org.hibernate.HibernateException;
import org.hibernate.Query;

import java.util.List;

public class ComputerDaoImpl extends BaseDaoImpl implements ComputerDao {
    /**
     * 重载父类的该方法
     * 分页查看，获取总记录数。
     */
    public int totalPage(String className) {
        String hql = "select count(*) from "+ className;
        Query query = this.getSession().createQuery(hql);
        int total = Integer.parseInt(query.list().get(0).toString());
        return total;
    }

    /**
     * 分页查询,显示首页
     * @param className
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public List<Computer> selectByPage(String className, int pageNo, int pageSize) {
        String hql = "from "+className;
        Query query =this.getSession().createQuery(hql);
        query.setFirstResult((pageNo - 1) * pageSize);//每页显示的第一条记录
        query.setMaxResults(pageSize);//每页显示的记录数
        return query.list();
    }

    @Override
    public boolean delectComputer(Computer computer) {
        boolean flag = false;
        try{
            getSession().delete(computer);
            getSession().flush();
            flag = true;
        }catch(HibernateException e){
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public Computer selectById(Integer id) {
        Computer computer = (Computer)getSession().get(Computer.class, new Integer(id));
        return computer;
    }

    @Override
    public boolean add(Computer computer) {
        boolean flag = false;
        try{
            getSession().save(computer);
            flag = true;
        }catch(HibernateException e){
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public boolean update(Computer computer) {
        boolean flag = false;
        try{
            getSession().update(computer);
            flag = true;
        }catch(HibernateException e){
            e.printStackTrace();
        }
        return flag;
    }

}
